<?php


namespace app\common\service;

use app\admin\service\ArrayService;
use app\common\wdt\WdtClient;

/**
 *  旺店通服务
 * @package app\common\service
 */
class WdtService
{
    // const SID = 'apidevnew2';
    // const APP_KEY = 'yyc02-test';
    // const APP_SECRET = 'f931d7428';
    // const DOMAIN = 'http://sandbox.wangdian.cn';
    const SID = 'yyc02';
    const APP_KEY = 'yyc02';
    const APP_SECRET = '98cb83e389b42bc40a3b164014c9a0b8';
    const DOMAIN = 'https://api.wangdian.cn';
    const SERVER_URL = self::DOMAIN . '/openapi2/';

    public static function getOldClient()
    {
        $c = new WdtClient;
        $c->sid = self::SID;
        $c->appkey = self::APP_KEY;
        $c->appsecret = self::APP_SECRET;
        return $c;
    }

    /**
     *
     * trade_query.php（查询旧的账号历史订单管理）
     * @param $trade_no
     * @return false|\stdClass|string|null
     * @throws \Exception
     */
    public static function queryOldHistoryOrder($trade_no)
    {
        $c = self::getOldClient();

        $c->gatewayUrl = self::SERVER_URL . 'his_trade_query.php';


        $c->putApiParam('src_tid', $trade_no);
//        $c->putApiParam('logistics_no', $trade_no);
//        $c->putApiParam('start_time', '2023-12-18 14:20:00');
//        $c->putApiParam('end_time', '2023-12-18 15:20:00');

        return $c->wdtOpenApi();
    }

    /**
     *
     * trade_query.php（查询订单管理）
     * @param $trade_no
     * @return false|\stdClass|string|null
     * @throws \Exception
     */
    public static function queryHistoryOrder($trade_no)
    {
        $c = self::getClient();

        $c->gatewayUrl = self::SERVER_URL . 'his_trade_query.php';


        $c->putApiParam('src_tid', $trade_no);

        return $c->wdtOpenApi();
    }

    public static function getClient()
    {
        $c = new WdtClient;
        $wdt_info = sysconfig('wdt');
//        die(var_dump($wdt_info));
        $c->sid = $wdt_info['wdt_sid'];
        $c->appkey = $wdt_info['wdt_app_key'];
        $c->appsecret = $wdt_info['wdt_app_secret'];
//        $c->sid = self::SID;
//        $c->appkey = self::APP_KEY;
//        $c->appsecret = self::APP_SECRET;
        return $c;
    }


    /**
     *
     * trade_query.php（查询旧订单）
     * @param $trade_no
     * @return false|\stdClass|string|null
     * @throws \Exception
     */
    public static function queryOldOrder($trade_no)
    {
        $c = self::getOldClient();

        // $c->gatewayUrl = 'http://sandbox.wangdian.cn/openapi2/shop.php';
        // $c->putApiParam('shop_no', 'yyc02-test');

        $c->gatewayUrl = self::SERVER_URL . 'trade_query.php';


        $c->putApiParam('src_tid', $trade_no);
//        $c->putApiParam('start_time', '2023-12-18 14:20:00');
//        $c->putApiParam('end_time', '2023-12-18 15:20:00');

        return $c->wdtOpenApi();
    }

    /**
     *
     * trade_query.php（查询订单管理）
     * @param $trade_no
     * @return false|\stdClass|string|null
     * @throws \Exception
     */
    public static function queryOrder($trade_no, $is_history = false)
    {
        $c = self::getClient();

        $query = 'trade_query.php';
        if ($is_history) {
            $query = 'his_trade_query.php';
        }
        $c->gatewayUrl = self::SERVER_URL . $query;

        if (ArrayService::startWith($trade_no, 'JY')) {
            $c->putApiParam('trade_no', $trade_no);
        } else {
            $c->putApiParam('src_tid', $trade_no);
        }


        return $c->wdtOpenApi();
    }

    public static function queryOrderByLogisticsNo($logistics_no, $is_history = false)
    {
        $c = self::getClient();
        $query = 'trade_query.php';
        if ($is_history) {
            $query = 'his_trade_query.php';
        }
        $c->gatewayUrl = self::SERVER_URL . $query;

        $c->putApiParam('logistics_no', $logistics_no);
        return $c->wdtOpenApi();
    }

    public static function testQueryOrder($trade_no)
    {
        $c = self::getClient();

        // $c->gatewayUrl = 'http://sandbox.wangdian.cn/openapi2/shop.php';
        // $c->putApiParam('shop_no', 'yyc02-test');

        $c->gatewayUrl = self::SERVER_URL . 'trade_query.php';

//        $c->putApiParam('trade_no', $trade_no);
        $c->putApiParam('src_tid', $trade_no);
//        $c->putApiParam('logistics_no', 'JT2924862679390');
//        $c->putApiParam('start_time', '2023-06-06 15:24:00');
//        $c->putApiParam('end_time', '2023-06-06 15:26:00');

        return $c->wdtOpenApi();
    }



    /**
     * @param $trade_no
     * @param $type int 1单号 2物流单号
     * @return array
     * @throws \Exception
     */
    public static function queryOrderRes($trade_no, $type = 1)
    {
        if ($type == 1) {
            $json = self::queryOrder($trade_no);
            if (!self::isSuccess($json)) {
                $json = self::queryOrder($trade_no, true);
            }
        } else {
            $json = self::queryOrderByLogisticsNo($trade_no);
            if (!self::isSuccess($json)) {
                $json = self::queryOrderByLogisticsNo($trade_no, true);
            }
        }
        $result = ['total_count' => 0, 'trades' => []];
        if ($json) {
//             die($json);
            $res = json_decode($json, true);
            $result['total_count'] = $res['total_count'];
            $order_list = [];
            if ($res['total_count'] > 0) {
                foreach ($res['trades'] as $order) {
                    $remark = $order['cs_remark'];

                    $shop_name = $order['shop_name'];
                    $goods = [];
                    foreach ($order['goods_list'] as $item) {
                        $goods[] = [
                            'spec_no' => $item['suite_name'],//组合装名称
                            'order_price' => $item['order_price'],
                            'price' => $item['price'],
                            'goods_name' => $item['goods_name'],
                            'num' => $item['num'],
                            'barcode' => $item['barcode'],
                            'total_price' => $item['share_amount'],
                        ];
                    }
                    $logistics_no = '';
                    if (array_key_exists('logistics_no', $order)) {
                        $logistics_no = $order['logistics_no'];
                    }
                    $order_list[] = [
                        'trade_no' => $order['src_tids'],
                        'platform_id' => $order['platform_id'],
                        'pay_time' => $order['pay_time'],
                        'to_deliver_time' => $order['to_deliver_time'],
                        'logistics_no' => $logistics_no,
                        'receivable' => $order['receivable'],
                        'cs_remark' => $remark,
                        'shop_name' => $shop_name,
                        'goods_list' => $goods,


                    ];
                }
            }
            $result['trades'] = $order_list;

        }
        return $result;
    }

    private static function isSuccess($json)
    {
        if ($json) {
            $res = json_decode($json, true);
            if ($res['total_count'] > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查询旧订单
     * @param $trade_no
     * @param $type int 1单号 2物流单号
     * @return array
     * @throws \Exception
     */
    public static function queryOldOrderRes($trade_no, $type = 1)
    {

        $json = self::queryOldOrder($trade_no);
        if (!self::isSuccess($json)) {

            $json = self::queryOldHistoryOrder($trade_no);
        }


        $result = ['total_count' => 0, 'trades' => []];
        if ($json) {
//             die($json);
            $res = json_decode($json, true);
            $result['total_count'] = $res['total_count'];
            $order_list = [];
            if ($res['total_count'] > 0) {
                foreach ($res['trades'] as $order) {
                    $remark = $order['cs_remark'];

                    $shop_name = $order['shop_name'];
                    $goods = [];
                    foreach ($order['goods_list'] as $item) {
                        $goods[] = [
                            'spec_no' => $item['suite_name'],//组合装名称
                            'order_price' => $item['order_price'],
                            'price' => $item['price'],
                            'goods_name' => $item['goods_name'],
                            'num' => $item['num'],
                            'barcode' => $item['barcode'],
                            'total_price' => $item['share_amount'],
                        ];
                    }
                    $logistics_no = '';
                    if (array_key_exists('logistics_no', $order)) {
                        $logistics_no = $order['logistics_no'];
                    }
                    $order_list[] = [
                        'trade_no' => $order['src_tids'],
                        'platform_id' => $order['platform_id'],
                        'pay_time' => $order['pay_time'],
                        'to_deliver_time' => $order['to_deliver_time'],
                        'logistics_no' => $logistics_no,
                        'receivable' => $order['receivable'],
                        'cs_remark' => $remark,
                        'shop_name' => $shop_name,
                        'goods_list' => $goods,


                    ];
                }
            }
            $result['trades'] = $order_list;

        }
        return $result;
    }

    public static function getShop($shop_no)
    {
        $c = self::getClient();

        $c->gatewayUrl = self::SERVER_URL . 'shop.php';

        $c->putApiParam('shop_no', $shop_no);
        return $c->wdtOpenApi();
    }
}
